<template>
  <div class="placeOrder warp">
    <div class="poAddressList">
      <div class="poAddListTit">
        <span>请选择收货地址</span>
        <span @click="newAddressFn">新增地址</span>
      </div>
      <div class="poAddListBox" v-if="addressData.length === 0">
        <span>暂无收货信息</span>
      </div>
      <div class="poAddListBox" v-if="addressData.length !== 0">
        <div class="title">收货人信息：</div>
        <div class="addressItem">
          <div class="addressInfo">
            <span class="userName">{{ cuurentAddress.receiveName }}</span>
            <span class="userAddress">{{ cuurentAddress.receiveAdress }} {{ cuurentAddress.address }}</span>
            <span class="userPhone">{{ cuurentAddress.receivePhone }}</span>
          </div>
          <span
            class="changeAddress"
            @click="showChangeAddress"
          >
            <svg-icon style="width: 16px;height: 16px;" name="exchange" />
            切换
          </span>
        </div>
      </div>
    </div>
    <!-- 订单商品信息 -->
    <div class="shoplist">
      <div class="shopTitle">请确认订单信息</div>
      <ShopOrder
        v-for="item in settlement.shops"
        :key="item.shopId"
        :shopsData="item"
      >
        <template #coupon>
          <div class="couponContainer">
            <div
              class="couponItem"
              v-for="(coupon, index) of item.shopCoupons"
              :key="index"
            >
              <CouponBox
                :type="'商家券'"
                :couponItem="coupon"
                :isSelect="coupon.checked"
                @coupon-select="couponSelect"
              />
            </div>
          </div>
        </template>
      </ShopOrder>
    </div>
    <!-- 优惠券信息 -->
    <!-- 平台券 -->
    <div class="couponContainer" v-if="settlement.coupons.length">
      <p>平台券</p>
      <div
        class="couponItem"
        v-for="(item, index) of settlement.coupons"
        :key="index"
      >
        <CouponBox
          :type="'平台券'"
          :couponItem="item"
          :isSelect="item.checked"
          @coupon-select="couponSelect"
        />
      </div>
    </div>
    <div class="payBox">
      <div class="payTit">选择支付方式</div>
      <div class="payList">
        <!--            <span :class="{payActive: payType === 'alipay'}" @click="selectPay('alipay')">-->
        <!--              <i class="iconfont">&#xe627;</i>-->
        <!--              <b class="iconfont">&#xe612;</b>-->
        <!--              支付宝支付-->
        <!--            </span>-->
        <span
          class="typeBox"
          :class="{payActive: payType === 'weChat'}"
          @click="selectPay('weChat')"
        >
          <i class="iconfont">&#xe686;</i>
          <b class="iconfont">&#xe612;</b>
          微信支付
        </span>
      </div>
    </div>
    <div class="placeOrderBtn">
      <div class="payInfo">
        <span>运费：+¥{{ payInfoExtra.distributionPrice.toFixed(2) }}</span>
        <span>平台优惠：-￥{{ payInfoExtra.couponAmount.toFixed(2) }}</span>
        <span>商家优惠：-￥{{ payInfoExtra.couponShopAmount.toFixed(2) }}</span>
        <span>需付款：<b>￥{{ totalPrice.toFixed(2) }}</b></span>
      </div>
      <el-button
        class="submitOrder"
        :class="{unDisButton: disabledSubmit}"
        :loading="loading.submitOrder"
        @click="() => {
          if (disabledButton) {
            clickTips()
          } else {
            clickPayOrder()
          }
        }"
      >提交订单</el-button>
    </div>
    <!-- 付款提示 -->
    <el-dialog
      title="请在1小时内完成付款，否则订单会被系统取消"
      v-model="visible.payment"
      width="30%">
      <div class="payment">
        <div class="paymentBox">
          <div class="successBox">
            <span>支付成功请点击</span>
            <el-button type="primary" plain>已完成付款</el-button>
          </div>
          <div class="errorBox">
            <span>遇到问题请点击</span>
            <el-button type="primary">重新付款</el-button>
          </div>
        </div>
        <div class="paymentInfo">
          <p>注：重新付款前，请关闭之前的付款页面</p>
          <p>如有疑问或需要帮助，请进入<b>帮助中心</b>或联系<b>在线客服</b></p>
        </div>
      </div>
    </el-dialog>
    <!-- 微信支付 -->
    <el-dialog
      class="weChat"
      title="微信支付"
      v-model="visible.wechatPay"
      :before-close="handleClose"
      width="500px">
      <div class="qCode">
        <div class="wechatTitle">
          <div class="tips">
            <p>请使用微信扫一扫</p>
            <p>扫描二维码支付</p>
          </div>
          <div>￥{{ payInfo.money }}</div>
        </div>
        <img class="code" :src="payInfo.url" alt="" />
      </div>
    </el-dialog>
    <!-- 新建收货地址 -->
    <el-dialog
      v-model="visible.address"
      :title="dialogAddressTypeTitle"
      width="630px">
      <AddAddress
        :data="addressForm"
        @hide-add-dialog="hideAddDialog"
        @cancel-add="closeAdd"
      />
    </el-dialog>
    <!-- 切换地址 -->
    <el-dialog
      title="选择收货地址"
      v-model="visible.updateAddress"
      :close-on-click-modal="false"
      :destroy-on-close="false"
    >
      <ul class="addressTable">
        <li
          class="addressListItem"
          v-for="(item, index) of addressData"
          :key="index"
          :class="{
            addressActive: cacheCurrentAddress.receiveId === item.receiveId
          }"
          @click="cacheCurrentAddress = item"
        >
          <div class="top com">
            <div class="left">姓名：
              <span>{{ item.receiveName }}</span> <span>{{ item.receivePhone }}</span>
            </div>
            <div
              class="setDef"
              :class="{colorActive: item.ifDefault}"
              @click="changeAddress(item)"
            >编辑</div>
          </div>
          <div class="bottom com">
            <div class="left">
              地址：<span>{{ item.receiveAdress }} {{ item.address }}</span>
            </div>
            <span v-if="item.ifDefault" class="defTip">默认地址</span>
            <div
              class="setDef"
              v-if="!item.ifDefault"
              @click="setDefAddress(item)"
            >设为默认地址</div>
          </div>
        </li>
      </ul>
      <template #footer>
        <el-button
          class="combtns"
          @click="visible.updateAddress = false"
        >取消</el-button>
        <el-button
          class="combtns btnBlack"
          @click="setChangeAddress"
        >确认</el-button>
      </template>
    </el-dialog>
    <!-- 支付失败 -->
    <el-dialog
      title="温馨提示"
      v-model="visible.payFail"
      width="300px">
      <div class="errorDialog">
        <span class="iconfont">&#xe620;</span>
        <p>您的订单支付失败</p>
      </div>
      <template #footer>
        <el-button
          class="btns"
          @click="toOrder"
        >查看订单</el-button>
        <el-button
          class="btns pay"
          type="primary"
          @click="rePayOrder"
        >重新支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineComponent, onBeforeMount, onMounted, reactive, ref, shallowRef } from 'vue'
import { useUser } from '@/store/user'
import { useCart } from '@/store/cart'
import { useRouter } from 'vue-router'

import { TextToCode } from 'element-china-area-data'

import AddAddress from '@/components/orderInfo/addAddress'
import ShopOrder from '@/views/placeOrder/components/shopOrder.vue'
import CouponBox from '@/views/placeOrder/components/couponBox.vue'
import SvgIcon from '@/components/svgIcon/index.vue';

import {
  getAllAddressList,
  addAddress,
  updateAddress
} from '@/api/user/address.js'
import {
  orderSubmit,
  orderPayCode,
  getSettlement,
  getGroupSettle,
  checkOrderResult
} from '@/api/user/order.js'
import {
  getCartList,
  deleteCartItem
} from '@/api/user/cart.js'



defineComponent({
  name: 'PlaceOrderIndex'
})

const userStore = useUser()
const cartStore = useCart()

const router = useRouter();

/**
 * 组件visible控制集合
 */
const visible = reactive({
  address: false,
  updateAddress: false,
  payment: false,
  wechatPay: false,
  payFail: false,
})

/**
 * 组件loading控制集合
 * @property {boolean} submitOrder 订单提交
 */
const loading = reactive({
  submitOrder: false,
})

/**
 * 
 */
const timer = reactive({
  chatPay: null,
})

/**
 * 订单优惠相关数据
 * @property {number} distributionPrice 总运费
 * @property {number} couponAmount 平台券总折扣
 * @property {number} couponShopAmount 商家券总折扣
 */
const payInfoExtra = reactive({
  distributionPrice: 0,
  couponAmount: 0,
  couponShopAmount: 0
})
// 订单总价
const totalPrice = shallowRef(0)

const addressData = ref([]);
const addressForm = ref({});
const cuurentAddress = reactive({
  receiveId: null,
  receiveName: '',
  receivePhone: '',
  receiveAdress: '',
  address: ''
})
const cacheCurrentAddress = ref({});
const dialogAddressTypeTitle = shallowRef('');
// 获取地址列表
function getAddressList () {
  getAllAddressList({
    page: 1,
    pageSize: 100
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      addressData.value = res.data.list
      if (addressData.value.length === 1) { // 只有1条，默认为收货地址
        initCurrentAddress(addressData.value[0])
        return
      }
      addressData.value.forEach((item, index) => {
        if (item.ifDefault) { // 如果有默认地址时
          initCurrentAddress(item)
        } else if (index === 0) { // 没有则优先选择第一个地址
          initCurrentAddress(item)
        }
      })
    }
  }).catch(err => {
    ElMessage.error(err.message)
  })
}



// 设置收货渲染数据
function initCurrentAddress (item = {}) {
  cuurentAddress.receiveId = item.receiveId || null
  cuurentAddress.receiveName = item.receiveName || ''
  cuurentAddress.receivePhone = item.receivePhone || ''
  cuurentAddress.receiveAdress = item.receiveAdress || ''
  cuurentAddress.address = item.address || ''
}
// 新增/修改 地址
function hideAddDialog () {
  let params = {
    receiveName: addressForm.value.receiveName,
    receivePhone: addressForm.value.receivePhone,
    receiveAdress: addressForm.value.receiveAdress,
    address: addressForm.value.address,
    label: '',
    ifDefault: addressForm.value.ifDefault ? 1 : 0
  }
  if (addressForm.value.receiveId) {
    params.receiveId = addressForm.value.receiveId
  }
  let fn = addressForm.value.receiveId ? updateAddress : addAddress
  fn(params).then(response => {
    const res = response.data
    if (res.code === '200') {
      ElMessage.success('操作成功')
      addressData.value = []
      userStore.setAreaCode([])
      getAddressList()
      if (addressForm.value.ifDefault) {
        if (router.currentRoute.value.query.type) {
          getSetProList()
        } else {
          getWorkSettlement()
        }
      }
    }
  }).catch(err => {
    ElMessage.error(err.message)
  }).finally(() => visible.address = false)
}
// 取消新增地址
function closeAdd () {
  visible.address = false
}
// 新增地址
function newAddressFn () {
  userStore.setAreaCode([])
  dialogAddressTypeTitle.value = '新增收货地址'
  visible.address = true
}
function showChangeAddress () {
  visible.updateAddress = true
}

// 修改收货地址
function setChangeAddress () {
  initCurrentAddress(cacheCurrentAddress.value)
  visible.updateAddress = false
  if (router.currentRoute.value.query.type) {
    getSetProList()
  } else {
    getWorkSettlement()
  }
}
// 修改地址信息
function changeAddress (item) {
  let addressData = item.receiveAdress.split('-')
  let areaData = []
  addressData[0] && areaData.push(TextToCode[addressData[0]].code)
  addressData[0] && areaData.push(TextToCode[addressData[0]][addressData[1]].code)
  addressData[0] && areaData.push(TextToCode[addressData[0]][addressData[1]][addressData[2]].code)
  userStore.setAreaCode(areaData)

  addressForm.value = item
  dialogAddressTypeTitle.value = '修改收货地址'
  visible.address = true
}
// 设置默认地址
function setDefAddress (item) {
  item.ifDefault = 1
  // this.seNewAddress(item)
  updateAddressFun()
}
// 更新地址
function updateAddressFun () {
  visible.updateAddress = false
  updateAddress({
    receiveId: addressForm.value.receiveId,
    receiveName: addressForm.value.receiveName,
    receivePhone: addressForm.value.receivePhone,
    receiveAdress: addressForm.value.receiveAdress,
    address: addressForm.value.address,
    label: '',
    ifDefault: addressForm.value.ifDefault
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      ElMessage.success('地址修改成功')
      addressData.value = []
      userStore.setAreaCode([])
      getAddressList()
    }
  }).catch(err => {
    ElMessage.error(err.message)
  })
}

let groupBuyInfo = ref({})
// 拼团商品结算查询
function getWorkSettlement () {
  groupBuyInfo.value.receiveId = cuurentAddress.receiveId
  payInfoExtra.distributionPrice = 0

  getGroupSettle(groupBuyInfo.value).then(response => {
    const res = response.data
    if (res.code === '200') {
      successBackSettlement(res)
    }
  }).catch(err => {
    ElMessage.error(err.message)
  })
}

let shopInfo = ref([]);
// 查询结算产品列表
function getSetProList () {
  payInfoExtra.distributionPrice = 0
  getSettlement({
    type: router.currentRoute.value.query.type,
    shops: shopInfo.value,
    ifWork: parseInt(router.currentRoute.value.query.ifWork),
    receiveId: cuurentAddress.receiveId
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      successBackSettlement(res)
    }
  }).catch(err => {
    ElMessage.error(err.message)
    router.back()
  })
}

let settlement = ref({
  coupons: [],
  shops: []
})
let disabledSubmit = shallowRef(false);
// 结算查询成功回调
function successBackSettlement (res) {
  disabledSubmit.value = false
  settlement.value = res.data
  settlement.value.coupons.forEach((item, index) => {
    item.index = index
    item.type = 1
    item.discountAmount = 0
  })
  settlement.value.shops.forEach(item => {
    // 处理收获地址是否符合商家配送范围内
    if (item.receiveNotMatch) {
      disabledSubmit.value = item.receiveNotMatch
      clickTips()
    }
    // 处理商家券
    item.shopCoupons = item.shopCoupons.map((i, index) => {
      i.index = index
      i.type = 2 // type 1平台券 2商家券
      i.uniWebId = `${item.shopId}+${index}` // 创建一个前端单方面的唯一值，处理选中状态
      i.shopId = item.shopId // 方便后续确定优惠券
      i.discountAmount = 0
      return i
    })
    item.totalAfterDiscount = item.total
    payInfoExtra.distributionPrice += Number(item.distribution.distributionPrice) || 0
  })
  getTotal()
}
// 选择优惠券
function couponSelect (val) {
  if (val.type === 1) {
    couponItemTap(val)
  } else {
    shopCouponItemTap(val)
  }
}
// 当前操作的优惠券所在店铺的索引
let currentShop = reactive({
  index: ''
})
// 选中的平台券
let currentCoupon = ref({});
// 商家优惠券
let shopCoupons = ref([]);
// 商家券 本方法参考uniapp代码的同名方法
function shopCouponItemTap (coupon) {
  currentShop.index = settlement.value.shops.map(item => {
    return item.shopId
  }).indexOf(coupon.shopId)

  // 取消选择优惠券
  if (coupon.checked) {
    coupon.checked = false
    coupon.discountAmount = 0
    settlement.value.shops[currentShop.index].totalAfterDiscount = settlement.value.shops[currentShop.index].total
    settlement.value.shops[currentShop.index].currentCoupon = {}
    settlement.value.shops[currentShop.index].skus.forEach(item => {
      item.buyerShopCouponId = null
    })
    shopCoupons.value = []
    getTotal()
    return false
  }

  if (settlement.value.shops[currentShop.index].total < coupon.fullMoney) {
    ElMessage.warning('不满足优惠券使用条件！')
  } else if (coupon.couponType === 1 && settlement.value.shops[currentShop.index].total < coupon.reduceMoney) {
    ElMessage.warning('不可使用大于商品金额的优惠劵！')
  } else {
    // 选择优惠券
    if (currentCoupon.value.couponId !== 0) {
      ElMessage.warning('此券不可与平台券叠加！')
      return false
    }
    if (coupon.couponType === 1) {
      if (coupon.reduceMoney >= settlement.value.shops[currentShop.index].total) {
        ElMessage.warning('优惠券优惠金额不能大于等于合计金额！')
        return false
      }
    }

    let useCoupon = useShopCoupon(currentShop.index, coupon.index)
    if (useCoupon) {
      // 确认使用当前点击的商家券，先将所有的商家券取消选中
      for (let i = 0; i < shopCoupons.value.length; i++) {
        shopCoupons.value[i].checked = false
      }
      shopCoupons.value = []

      coupon.checked = true
      settlement.value.shops[currentShop.index].id = coupon.id
      settlement.value.shops[currentShop.index].currentCoupon = coupon
      settlement.value.shops[currentShop.index].skus.forEach(item => {
        if (item.buyerShopCouponId > 0 && item.buyerShopCouponId !== coupon.shopCouponId) {
          item.buyerShopCouponId = null
        }
      })
      shopCoupons.value.push(coupon)
    } else {
      settlement.value.shops[currentShop.index].totalAfterDiscount = settlement.value.shops[currentShop.index].total
    }
    getTotal()
  }
}
// 平台券 本方法参考uniapp的同名方法
function couponItemTap (coupon) {
  if (!coupon.checked && shopCoupons.value.length) { // 判断商家券情况
    ElMessage.warning('不可与商家券叠加使用！')
    return false
  }
  // 已选中的情况下取消选中
  if (coupon.checked) {
    coupon.checked = false
    coupon.discountAmount = 0

    currentCoupon.value = null
    settlement.value.shops.forEach(shopItem => {
      if (shopItem.skus) {
        shopItem.skus.forEach(skuItem => {
          skuItem.buyerCouponId = null
        })
      }
    })
    getTotal()
  } else {
    // 先把所有已选中的平台优惠券改为未选中
    settlement.value.coupons.forEach((item) => {
      item.checked = false
    })
    let totalPrice = 0 // 订单总价
    let shopsLen = settlement.value.shops.length // 结算页店铺数量
    let matchCouponSkuList = []
    for (let i = 0; i < shopsLen; i++) {
      let matchCouponNormalPrice = 0
      let priceCount = 0
      const curShop = settlement.value.shops[i]
      let skuLen = curShop.skus.length
      let tmpPriceSkuList = []
      for (let j = 0; j < skuLen; j++) {
        const curSku = curShop.skus[j]
        if (curSku.priceId > 0) {
          priceCount++
        }
        const ids = coupon.ids
        if (ids.indexOf(curSku.productId) > -1) {
          if (curSku.priceId > 0) {
            tmpPriceSkuList.push(curSku)
          } else {
            matchCouponSkuList.push(curSku)
            matchCouponNormalPrice = matchCouponNormalPrice + curSku.price * curSku.number
          }
        }
      }
      if (priceCount === tmpPriceSkuList.length) {
        totalPrice += curShop.priceAfterDiscount
        matchCouponSkuList = matchCouponSkuList.concat(tmpPriceSkuList)
      }
      totalPrice += matchCouponNormalPrice
    }
    // 结算额度
    const settlementTotal = settlement.value && settlement.value.shops[currentShop.index] && settlement.value.shops[currentShop.index].total
    if (settlementTotal < coupon.fullMoney) {
      ElMessage.warning('不满足优惠券使用条件！')
    }
    if (coupon.couponType === 1 && coupon.reduceMoney >= totalPrice) {
      ElMessage.warning('不可使用大于等于合计金额的优惠劵！')
      return false
    }
    // 如果是折扣券，需要记录，在什么基数上打折
    coupon.useMoney = totalPrice
    currentCoupon.value = coupon
    matchCouponSkuList.forEach(item => {
      item.buyerCouponId = coupon.couponId
    })
    getTotal()
    // 选中优惠券
    coupon.checked = true
  }
}
// 校验商家券是否满足使用条件
// 后续该方法的维护直接从uniapp端的代码复制过来
function useShopCoupon (shopIndex, couponIndex) {
  const curShop = settlement.value.shops[shopIndex]
  curShop.totalAfterDiscount = 0
  let curCoupon
  if (curShop.shopCoupons && curShop.shopCoupons.length > 0) {
    curCoupon = curShop.shopCoupons[couponIndex]
  }
  if (!curCoupon) {
    return false
  }
  let useCoupon = false
  let matchCouponNormalSkuList = []
  let matchCouponPriceSkuList = []
  if (curCoupon.applyType !== 1) {
    const ids = curCoupon.ids
    let skuLength = curShop.skus.length
    // 符合优惠券商品列表中的普通sku价格综合
    let matchCouponNormalPrice = 0
    // 符合定价捆绑且在优惠券商品列表中的价格综合
    let matchCouponPricePrice = 0
    // 符合定价捆绑活动的sku数量
    let priceCount = 0
    for (let idx = 0; idx < skuLength; idx++) {
      let curSku = curShop.skus[idx]
      if (curSku.priceId > 0) {
        priceCount++
      }
      if (ids.indexOf(curSku.productId) > -1) {
        if (curSku.priceId > 0) {
          matchCouponPriceSkuList.push(curSku)
        } else {
          matchCouponNormalSkuList.push(curSku)
          matchCouponNormalPrice = matchCouponNormalPrice + curSku.price * curSku.number
        }
      }
    }
    // 如果定价捆绑的所有sku都符合优惠券
    if (priceCount === matchCouponPriceSkuList.length) {
      matchCouponPricePrice = curShop.priceAfterDiscount
    }
    // 符合的sku的price加起来是否满足满减的条件
    const priceFinal = matchCouponPricePrice + matchCouponNormalPrice
    if (priceFinal < curCoupon.fullMoney || (curCoupon.couponType === 1 && priceFinal <= curCoupon
      .reduceMoney)) {
      return false
    }
    // 判断是满减，还是折扣
    if (curCoupon.couponType === 1) {
      curShop.totalAfterDiscount = curShop.total - curCoupon.reduceMoney
      curCoupon.discountAmount = curCoupon.reduceMoney
      useCoupon = true
    } else {
      // 打折后优惠抵扣的金额
      let priceDiscount = (priceFinal * ((10 - curCoupon.reduceMoney) / 10)).toFixed(2)
      let tmpTotal = curShop.total - priceDiscount
      if (tmpTotal.toFixed(2) >= 0.01) {
        curShop.totalAfterDiscount = tmpTotal.toFixed(2)
        curCoupon.discountAmount = priceDiscount
        useCoupon = true
      }
    }
    if (useCoupon) {
      // 满足的sku设置buyerShopCouponId
      if (priceCount === matchCouponPriceSkuList.length) {
        let length1 = matchCouponPriceSkuList.length
        for (let idx = 0; idx < length1; idx++) {
          matchCouponPriceSkuList[idx].buyerShopCouponId = curCoupon.shopCouponId
        }
      }
      let length2 = matchCouponNormalSkuList.length
      for (let idx = 0; idx < length2; idx++) {
        matchCouponNormalSkuList[idx].buyerShopCouponId = curCoupon.shopCouponId
      }
    }
  } else {
    if (curCoupon.couponType === 1) {
      if (curShop.total > curCoupon.reduceMoney) {
        curShop.totalAfterDiscount = curShop.total - curCoupon.reduceMoney
        curCoupon.discountAmount = curCoupon.reduceMoney
        useCoupon = true
      }
    } else {
      if (curShop.total > curCoupon.fullMoney) {
        let priceDiscount = (curShop.total * ((10 - curCoupon.reduceMoney) / 10)).toFixed(2)
        let tmpTotal = curShop.total - priceDiscount
        if (tmpTotal.toFixed(2) >= 0.01) {
          curShop.totalAfterDiscount = tmpTotal.toFixed(2)
          curCoupon.discountAmount = priceDiscount
          useCoupon = true
        }
      }
    }
    if (useCoupon) {
      let skuLength = curShop.skus.length
      for (let idx = 0; idx < skuLength; idx++) {
        curShop.skus[idx].buyerShopCouponId = curCoupon.shopCouponId
      }
    }
  }
  return useCoupon
}

/**
 * 计算总价，商家券的优惠计算，在调用本方法之前已经计算好在shops[].totalAfterDiscount
 * 本方法参考uniapp的方法即可
 */
function getTotal () {
  totalPrice.value = 0
  let shopSumPrice = 0
  let shopsLen = settlement.value.shops.length
  calcCouponShopAmount()

  for (let i = 0; i < shopsLen; i++) {
    totalPrice.value += parseFloat(settlement.value.shops[i].totalAfterDiscount)
    shopSumPrice += parseFloat(settlement.value.shops[i].totalAfterDiscount)
    // this.totalCount += settlement.value.shops[i].number
  }

  calcCouponAmount()
  if (currentCoupon.value) {
    totalPrice.value = shopSumPrice - payInfoExtra.couponAmount
  }
  // 加上每个商家的运费
  settlement.value.shops.forEach((item) => {
    totalPrice.value = totalPrice.value + (item.distribution.distributionPrice || 0)
  })
}

// 计算商家券优惠金额
function calcCouponShopAmount () {
  if (!shopCoupons.value || shopCoupons.value.length === 0) {
    payInfoExtra.couponShopAmount = 0
  }
  let tmpAmount = 0
  shopCoupons.value.forEach(coupon => {
    tmpAmount += coupon.discountAmount
  })
  payInfoExtra.couponShopAmount = tmpAmount
}
// 计算平台券优惠金额
function calcCouponAmount () {
  let tmpAmount = 0
  if (currentCoupon.value && JSON.stringify(currentCoupon.value) !== '{}') {
    if (currentCoupon.value.couponType === 1) {
      tmpAmount = currentCoupon.value.reduceMoney
    } else {
      tmpAmount = (currentCoupon.value.useMoney * ((10 - currentCoupon.value.reduceMoney) / 10)).toFixed(2)
    }
  }
  payInfoExtra.couponAmount = parseFloat(tmpAmount)
}

let payType = shallowRef('')
// 选择支付方式
function selectPay (type) {
  payType.value = type
}
function clickTips () {
  ElMessage.warning('当前地址不支持配送，请参考红色字提示！')
}
// 提交支付
function clickPayOrder () {
  visible.payFail = false
  if (!payType.value) {
    ElMessage.warning('请选择支付方式')
  } else if (cuurentAddress.receiveId === '') {
    ElMessage.warning('请选择您的收货地址')
  } else {
    let shops = []
    settlement.value.shops.forEach((shopItem, _i) => {
      let skus = []
      shopItem.skus.forEach((shopSkuItem, _n) => {
        if (shopSkuItem.selected) {
          skus.push({
            skuId: shopSkuItem.skuId,
            number: shopSkuItem.number,
            selected: shopSkuItem.selected,
            platformSeckillId: shopSkuItem.platformSeckillId,
            platformDiscountId: shopSkuItem.platformDiscountId,
            shopSeckillId: shopSkuItem.shopSeckillId,
            shopDiscountId: shopSkuItem.shopDiscountId,
            priceId: shopSkuItem.priceId,
            composeId: shopSkuItem.composeId,
            sceneId: shopSkuItem.sceneId,
            useMember: shopSkuItem.useMember,
            buyerCouponId: shopSkuItem.buyerCouponId,
            buyerShopCouponId: shopSkuItem.buyerShopCouponId
          })
        }
      })
      if (skus.length) {
        shops.push({
          id: shopItem.id,
          shopId: shopItem.shopId,
          remark: shopItem.remark,
          distribution: {
            distributionPrice: shopItem.distribution.distributionPrice,
            logisticsId: shopItem.distribution.logisticsId,
            distributionName: shopItem.distribution.distributionName
          },
          skus
        })
      }
    })
    let submitData = {
      shops: shops,
      receiveId: cuurentAddress.receiveId,
      price: totalPrice.value.toFixed(2),
      // 优惠总额
      discountPrice: parseFloat((payInfoExtra.couponAmount + payInfoExtra.couponShopAmount).toFixed(2) || 0),
      remark: settlement.value.shops[0].remark,
    }
    // 优惠总额 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    const query = router.currentRoute.value.query
    if (
      parseInt(query.activityType) === 1
      && parseInt(query.ifWork) !== 1
    ) {
      submitData.shopGroupWorkId = groupBuyInfo.value.shopGroupWorkId
      submitData.type = 1
      if (groupBuyInfo.value.collageId) {
        submitData.collageId = groupBuyInfo.value.collageId
        submitData.type = 2
      }
    } else if (parseInt(query.activityType) === 2) {
      submitData.shopSeckillId = shopInfo.value[0].shopSeckillId
      submitData.type = 3
    } else if (parseInt(query.activityType) === 3) {
      submitData.shopDiscountId = shopInfo.value[0].shopDiscountId
      submitData.type = 4
    }
    onOrderSubmit(submitData)
  }
}

/** 支付二维码弹窗相关数据 */
let payInfo = reactive({
  money: 0,
  url: '',
  orderId: null
});
// 提交订单
function onOrderSubmit (subData) {
  subData.couponId = currentCoupon.value.couponId > 0 ? currentCoupon.value.couponId : 0
  loading.submitOrder = true
  orderSubmit(subData).then(response => {
    const res = response.data
    if (res.code === '200') {
      payInfo.money = res.data.money
      payInfo.url = res.data.url
      payInfo.orderId = res.data.orderId
      if (Number(router.currentRoute.value.query.type || 0) === 2) {
        let ids = []
        subData.shops.forEach(i => {
          i.skus.forEach(j => {
            ids.push(j.skuId)
          })
        })
        deleteCartItem({ids}).then(res => {
          if (res.data.code === '200') {
            getTrolleyList()
          }
        })
      }
      visible.wechatPay = true
      timer.chatPay = setInterval(() => {
        checkPay(res.data)
      }, 3000)
    }
  }).catch(err => {
    ElMessage.error(err.message)
  }).finally(() => {
    loading.submitOrder = false
  })
}
// 查询订单是否支付成功
function checkPay (paramsData) {
  setTimeout(() => {
    checkOrderResult({
      collageId: paramsData.collageId,
      money: paramsData.money,
      orderId: paramsData.orderId,
      type: 1
    }).then(response => {
      const res = response.data
      if (res.code === '200') {
        if (res.data.code === 'SUCCESS') {
          ElMessage.success('支付成功！')
          clearInterval(timer.chatPay)
          getTrolleyList()
          // 支付有礼跳转
          router.push({
            path: '/orderResult',
            query: {
              orderId: paramsData.orderId
            }
          })
        }
      }
    }).catch(err => {
      clearInterval(timer.chatPay)
      ElMessage.error(err.message)
    })
  }, 0)
}
// 重新支付
function rePayOrder () {
  orderPayCode({ orderId: payInfo.orderId, type: 1 }).then(response => {
    const res = response.data
    if (res.code === '200') {
      payInfo.money = res.data.money;
      payInfo.url = res.data.url;
      payInfo.orderId = res.data.orderId
      visible.wechatPay = true;
      timer.chatPay = setInterval(() => {
        checkPay(res.data);
      }, 3000);
    }
  }).catch(err => ElMessage.error(err.message))
}
// 获取购物车列表
function getTrolleyList () {
  getCartList().then(response => {
    const res = response.data
    let cartNumber = 0
    if (res.data.length) {
      res.data.forEach(j => {
        cartNumber = cartNumber + j.skus.length
      })
    }
    cartStore.setShoppingCart(res.data)
    cartStore.setCartNumber(cartNumber)
  })
}
// 取消支付
function handleClose () {
  ElMessageBox('确认取消支付？')
    .then(_ => {
      clearInterval(timer.chatPay)
      visible.wechatPay = false
      visible.payFail = true
    })
    .catch(_ => {})
}
function toOrder () {
  router.push({
    path: '/myOrder'
  })
}

onBeforeMount(() => {
  const currentRoute = router.currentRoute.value;
  if (currentRoute.query.works) {
    groupBuyInfo.value = JSON.parse(currentRoute.query.works)
  }
  if (currentRoute.query.shops) {
    // this.paramShops = JSON.parse(currentRoute.query.shops)
    shopInfo.value= JSON.parse(currentRoute.query.shops)
  }
})

onMounted(() => {
  // 获取地址列表
  getAddressList()
  if (router.currentRoute.value.query.type) {
    getSetProList()
  } else {
    getWorkSettlement()
  }
})
</script>

<style lang="scss" scoped>
.placeOrder {
  margin: 20px auto;
  .poAddressList {
    width: 100%;
    border: 1px solid #F5F5F5;
    // padding: 20px;
    margin-bottom: 30px;
    box-sizing: border-box;
    .poAddListTit {
      height: 80px;
      background-color: #FAFAFA;
      display: flex;
      justify-content: space-between;
      align-items: center;
      span:nth-child(1) {
        color: #333333;
        font-size: 16px;
        margin-left: 30px;
      }
      span:nth-child(2) {
        color: $mainGlod;
        font-size: 14px;
        cursor: pointer;
        margin-right: 30px;
      }
    }
    .poAddListBox {
      height: 130px;
      margin:20px 30px 0 30px;
      font-family: Microsoft YaHei;
      .title{
        font-size: 16px;
        color: #333333;
      }
      .addressItem{
        height: 40px;
        margin: 30px auto 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .addressInfo{
          display: flex;
          align-items: center;
          cursor: default;
          .userName{
            display: block;
            width: 100px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: #B39259;
            background-color: rgba($color: #C5AA7B, $alpha: .1);
          }
          .userAddress{
            margin: 0 30px 0 20px;
            max-width: 400px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        .changeAddress{
          width: 100px;
          height: 40px;
          line-height: 40px;
          text-align: center;
          color: #FFEBC4;
          background-color: #333333;
          cursor: pointer;
        }
      }
    }
  }
  :deep(.el-dialog){
    // .el-dialog__body {
    //   background: #F8F8F8;
    // }
    .el-dialog__header {
      text-align: center;
    }
    .el-dialog__footer {
      text-align: center;
      .dialog-footer {
        text-align: center;
        button {
          height: 45px;
          width: 160px;
        }
      }
      .combtns{
        width: 200px;
        height: 50px;
        background: #F3F4F5;
        border-radius: 0px;
      }
      .btnBlack{
        color: $mainGlod;
        background: #333333;
      }
    }
  }
  .addressTable{
    width: 100%;
    max-height: 415px;
    overflow-y: auto;
    .addressListItem{
      height: 80px;
      padding: 15px 20px;
      margin-bottom: 15px;
      border: 1px solid #F3F4F5;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      .com{
        line-height: 25px;
        display: flex;
        font-size: 14px;
        font-family: Microsoft YaHei;
        color: #999999;
        .left{
          flex: 1;
        }
      }
      .left{
        span{
          color: #333333;
        }
      }
      .defTip{
        width: 70px;
        height: 25px;
        text-align: center;
        color: #FFF;
        background-color: $mainGlod;
        cursor: default;
      }
      .setDef{
        cursor: pointer;
      }
    }
    .addressActive{
      background: rgba(197, 170, 123, 0.26);
      border: 1px solid #C5AA7B;
    }
    .colorActive{
      color: $mainGlod;
    }
  }
  .shoplist{
    .shopTitle{
      line-height: 80px;
      padding-left: 30px;
      background-color: #FAFAFA;
    }
  }
  .orderList {
    background: #FCFCFC;
    border: 1px solid #E5E5E5;
    margin-bottom: 25px;
    .orderInfoTit {
      width: 100%;
      display: flex;
      height: 44px;
      line-height: 44px;
      color: #333333;
      font-size: 14px;
      font-weight: 400;
    }
    span {
      text-align: center;
    }
    span:nth-child(1) {
      width: 40%;
      text-align: left;
      padding-left: 125px;
      box-sizing: border-box;
    }
    span:nth-child(2) {
      width: 20%;
      text-align: left;
    }
    span:nth-child(3) {
      width: 15%;
    }
    span:nth-child(4) {
      width: 15%;
    }
    span:nth-child(5) {
      width: 10%;
    }
    span:nth-child(6) {
      width: 10%;
    }
  }
  .couponContainer{
    margin-bottom: 30px;
    height: 100%;
    margin-top: 30px;
    overflow: auto;
    box-sizing: border-box;
    border: 1px solid #F3F4F5;
    p{
      padding-left: 30px;
      line-height: 80px;
      font-size: 16px;
      background-color: #FAFAFA;
    }
    .couponItem {
      width: 280px;
      height: 88px;
      margin: 15px;
      float: left;
      cursor: pointer;
      position: relative;
      box-sizing: border-box;
      display: flex;
    }

    .svg-icon{
      width:100%;
      height:100%;
      position: absolute;
      z-index: -1;
    }
    .des{
      flex: 8;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .nums{
        flex: 4;
        text-align: right;
        .money{
          font-size: 40px;
        }
      }
      .cloumn{
        flex: 6;
        display: flex;
        flex-direction: column;
        margin-left: 8px;
      }
    }
    .aside{
      flex: 2;
      display: flex;
      justify-content: center;
      align-items: center;
      .checkBox{
        width: 20px;
        height: 20px;
        border: 1px solid #E8E9EB;
      }
    }
    .marginR{
      margin-right: 13px;
    }
  }
  .payBox {
    .payTit {
      padding-left: 30px;
      line-height: 80px;
      font-size: 16px;
      color: #333333;
      background-color: #FAFAFA;
    }
    .payList{
      height: 120px;
      padding: 0 20px;
      border: 2px solid #F3F4F5;
      display: flex;
      align-items: center;
      .typeBox{
        display: block;
        width: 150px;
        height: 60px;
        margin: 0 20px;
        color: #666666;
        font-size: 16px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        position: relative;
        i {
          font-size: 26px;
          margin-right: 5px;
        }
        b {
          color: $mainGlod;
          position: absolute;
          right: -1px;
          bottom: -1px;
          display: none;
        }
      }
      .payActive {
        border: 1px solid $mainGlod;
        b {
          display: block;
        }
      }
      span {
        border: 1px solid #E5E5E5;
        padding: 5px 10px;
        margin-right: 15px;
      }
      span:nth-child(1) {
        i:nth-child(1) {
          color: #40ba49;
          cursor: pointer;
        }
      }
      span:nth-child(2) {
        i {
          color:  #40ba49;
        }
      }
    }
  }
  // 提交订单部分
  .placeOrderBtn {
    margin-top: 50px;
    width: 100%;
    padding: 30px 0;
    .payInfo{
      padding: 0 15px;
      line-height: 70px;
      border: 2px solid #F3F4F5;
      display: flex;
      span {
        display: block;
        font-size: 14px;
        color: #333333;
        margin-left: 100px;
      }
      span:nth-child(1) {
        margin-left: 0;
      }
      span:nth-child(4) {
        b {
          color: $mainGlod;
        }
      }
    }
    .submitOrder{
      display: block;
      width: 200px;
      height: 50px;
      margin: 40px auto 0;
      padding: 0;
      background-color: #333;
      color: #FFEBC4;
      border-radius: 0;
    }
    .unDisButton{
      opacity: 0.6;
    }
  }
  .payment {
    width: 80%;
    margin: 0 auto;
    .paymentBox {
      margin-top: 50px;
      display: flex;
      justify-content: center;
      .successBox, .errorBox {
        width: 240px;
        text-align: center;
      }
      .successBox {
        border-right: 1px solid #DDDDDD;
        :deep(.el-button){
          border: 1px solid $mainGlod;
        }
      }
      span {
        display: block;
        margin-bottom: 20px;
      }
    }
    .paymentInfo {
      text-align: center;
      margin-top: 60px;
      p {
        font-size: 16px;
        color: #999999;
        line-height: 30px;
        b {
          color: #FF7800;
          cursor: pointer;
          font-weight: normal;
        }
      }
    }
  }
  // 微信支付弹框
  .weChat {
    .el-dialog__body{
      background: #FFFFFF;
      .qCode {
        .wechatTitle{
          width: 280px;
          margin: auto;
          padding: 10px 15px;
          color: #333;
          border: 2px solid #F3F4F5;
          display: flex;
          justify-content: space-around;
          align-items: center;
          .tips{
            flex: 1;
          }
        }
        .code{
          width: 280px;
          height: 280px;
          display: block;
          margin: 10px auto;
          border: 2px solid #F3F4F5;
        }
      }
    }
  }
  .errorDialog {
    text-align: center;
    span {
      font-size: 50px;
      color: red;
    }
    p {
      margin: 30px 0;
    }
  }
  .btns{
    border-radius: 0;
    background-color: #F3F4F5;
  }
  .pay{
    color: #FFEBC4;
    background-color: #333;
  }
  .remarksBox {
    display: flex;
    background: #F7F7F7;
    padding: 25px;
    border-radius: 8px;
    margin-bottom: 30px;
    .remarksInfo {
      width: 100%;
      :deep(.el-textarea__inner){
        width: 100%;
        height: 84px;
      }
    }
    .selectBox {
      margin-left: 70px;
      label {
        color: #666666;
        font-size: 16px;
        font-weight: normal;
      }
    }
    .shopTotal {
      color: $mainGlod;
      flex: 1;
      text-align: right;
    }
  }
}
</style>
